<template>
  <div id="productPage">
    <BreadcrumbComponent :breadcrumbItems="breadcrumbItems" />
    <TableFilter :config="filterConfig" @search="handleSearch" />
    <!-- 工具欄 -->
    <a-space>
      <a-dropdown>
        <a-button type="primary" :loading="exportLoading">
          <template #icon>
            <ExportOutlined />
          </template>
          導出
        </a-button>
        <template #overlay>
          <a-menu @click="handleExport">
            <a-menu-item key="filteredData"> 按篩選導出 </a-menu-item>
            <a-menu-item key="allData"> 全部導出 </a-menu-item>
          </a-menu>
        </template>
      </a-dropdown>
    </a-space>
    <div class="data-box">
      <a-table
        :columns="columns"
        :data-source="tableData"
        :pagination="pagination"
        :loading="loading"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'category'">
            <a-tag v-if="record.category == 'prescription'" color="green"
              >處方</a-tag
            >
            <a-tag v-else-if="record.category == 'cordyceps'" color="volcano"
              >蟲草</a-tag
            >
            <a-tag v-else-if="record.category == 'nest'" color="gold"
              >燕窩</a-tag
            >
            <a-tag v-else-if="record.category == 'angong'" color="red"
              >安宮系列</a-tag
            >
            <a-tag v-else-if="record.category == 'wyt'" color="magenta"
              >本廠</a-tag
            >
            <a-tag v-else-if="record.category == 'oem'" color="cyan">OEM</a-tag>
            <a-tag v-else-if="record.category == 'acupuncture'" color="blue"
              >針灸</a-tag
            >
            <a-tag v-else-if="record.category == 'tianjiu'" color="purple"
              >天灸</a-tag
            >
            <a-tag
              v-else-if="record.category == 'finished_goods'"
              color="orange"
              >成品</a-tag
            >
            <a-tag v-else-if="record.category == 'package'" color="lime"
              >套餐</a-tag
            >
            <a-tag v-else color="default">unknown</a-tag>
          </template>
          <template v-if="column.dataIndex === 'updatedAt'">
            {{ $formatDate(record.updatedAt) }}
          </template>
          <template v-if="column.key === 'action'">
            <a-button @click="handleEdit(record)">編輯</a-button>
          </template>
        </template>
      </a-table>
    </div>
    <!-- 修改模態框 -->
    <a-modal v-model:open="showModalEdit" title="產品信息編輯" :footer="null">
      <template #title>
        編輯產品信息
        <a-tag color="warning"
          ><template #icon>
            <ExclamationCircleOutlined />
          </template>
          ID: {{ editRecordId }}</a-tag
        >
      </template>
      <DynamicForm
        ref="editFormRef"
        :fieldConfig="editFieldConfig"
        @submit="handleEditSubmit"
        :formData="editFormData"
      />
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from "vue";
import { message } from "ant-design-vue";
import {
  ExportOutlined,
  ExclamationCircleOutlined,
} from "@ant-design/icons-vue";
import BreadcrumbComponent from "@/components/BreadcrumbComponent.vue";
import TableFilter from "@/components/TableFilter.vue";
import DynamicForm from "@/components/DynamicForm.vue";
import {
  tableColumns,
  filterFields,
  getEditFieldConfig,
} from "@/models/product";
import { createPagination } from "@/utils/pagination";
import { productApi } from "@/api";
import { useRouter, useRoute } from "vue-router";
import type { RouteLocationRaw } from "vue-router";
import { watchRouteQuery } from "@/utils/routeQueryWatcherUtil";

const breadcrumbItems = [{ url: "", name: "產品管理" }];
const columns = tableColumns;
const filterConfig = filterFields;
const editFieldConfig = ref<Record<string, any>>({});
const router = useRouter();
const route = useRoute();
const loading = ref(false);

const pagination = createPagination();

const tableData = ref([]);
const editRecordId = ref<number>(0);
const editFormData = reactive<any>({});

const fetchData = async (params?: any) => {
  loading.value = true;
  try {
    const {
      data: { list, page, limit, total },
    } = await productApi.getProductList(params);
    tableData.value = list || [];
    pagination.updatePagination(page, limit, total);
  } catch (error) {
    console.error("獲取產品列表失敗", error);
  } finally {
    loading.value = false;
  }
};
// 監聽路由變化,更新列表數據
watchRouteQuery(fetchData);
onMounted(() => {
  if (Object.keys(route.query).length > 0) {
    fetchData(route.query);
  }
});

const handleSearch = (params: any) => {
  router.push({ query: params });
};

// 編輯

const showModalEdit = ref(false);
const handleEdit = (record: any) => {
  if (Object.keys(editFieldConfig.value).length === 0) {
    editFieldConfig.value = getEditFieldConfig();
  }
  editRecordId.value = Number(record.id);
  Object.assign(editFormData, record);
  showModalEdit.value = true;
};

const editFormRef = ref();
const handleEditSubmit = async (data: any) => {
  try {
    await productApi.updateProduct(editRecordId.value, data);
    message.success("修改產品信息成功");
    showModalEdit.value = false;
    fetchData(route.query);
  } catch (error) {
    console.error("修改產品信息失敗", error);
  } finally {
    editFormRef.value?.resetLoading();
  }
};

const handleView = (record: any) => {
  router.push({ name: "ProductDetail", params: { id: record.id } });
};

const handleProductService = (record: any) => {
  router.push({
    name: "ProductService",
    params: { id: record.id },
    meta: { productData: 123 },
  } as RouteLocationRaw);
};

// 導出
const exportLoading = ref(false);
const handleExport = async ({ key }: { key: string }) => {
  let params: any = {};
  if (key === "filteredData") {
    params = route.query;
  }
  exportLoading.value = true;
  try {
    await productApi.exportProductList(params);
  } catch (error) {
    message.error("導出數據失敗");
  } finally {
    exportLoading.value = false;
  }
};
</script>

<style scoped></style>
